import React, { useEffect, useState } from "react";
import Checkbox from "../../../Checkbox";
import classnames from "classnames";
import { isPromise } from "@ct0/functions";
import type { CheckboxOption } from "../../../Checkbox/type";
import type { FieldBaseType } from "../../type";

const { CheckboxGroup } = Checkbox;

export default function CheckboxField({
  field,
  isValid,
  onChange,
}: {
  field: FieldBaseType<Array<string | number>>;
  isValid: boolean;
  onChange: (v: Array<string | number>) => void;
}) {
  const { value: propsValue, defaultValue, disabled, options } = field;

  const [opts, setOpts] = useState<Array<CheckboxOption<string | number>>>([]);

  useEffect(() => {
    if (typeof options == "undefined") return;
    else if (typeof options == "function") {
      const opt = options();
      if (isPromise(opt)) opt.then((r) => setOpts(r));
      else setOpts(opt as any);
    } else {
      setOpts(options);
    }
  }, [options]);

  const value = propsValue ?? defaultValue ?? [];

  return (
    <CheckboxGroup
      className={classnames({
        "ct0-formview-checkbox-invalid": !isValid,
      })}
      value={value}
      onChange={onChange}
      disabled={disabled}
      options={opts}
    />
  );
}
